#include "add.h"
#include "ui_add.h"
#include "myprotocol.h"
#include <QMessageBox>
#include <cstring>

Add::Add(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Add)
{
    ui->setupUi(this);
    this->setFixedSize(this->size().width(),this->size().height());
    this->setWindowIcon(QIcon(":/new/prefix1/Image/mesage.png"));
    this->setWindowTitle("ADD");
    QPalette qp = this->palette(); //重新拷贝一份和本对象palette相同的palette
    qp.setBrush(QPalette::Window,QBrush(QImage(":/new/prefix1/Image/Frame.jpg").scaled(this->size())));
    this->setPalette(qp);

    this->ui->add_btn->setIcon(QIcon(":/new/prefix1/Image/add.png"));
    this->ui->add_btn->setIconSize(QSize(this->ui->add_btn->size().width(),
                                         this->ui->add_btn->size().width()));

    this->socket = nullptr;
    this->ui->salary_line->setReadOnly(true);
    connect(this,&Add::my_add_signal,this,&Add::my_add_slot);
}

Add::~Add()
{
    delete ui;
}

void Add::set_socket(QTcpSocket *socket)
{
    this->socket = socket;
}

void Add::on_add_btn_clicked()
{
    if(this->ui->name_line->text().isEmpty())
    {
        QString error_str = "name is empty!";
        QMessageBox::critical(this, "error", error_str);
        return;
    }
    else if(this->ui->old_line->text().isEmpty())
    {
        QString error_str = "old is empty!";
        QMessageBox::critical(this, "error", error_str);
        return;
    }
    else if(this->ui->department_line->text().isEmpty())
    {
        QString error_str = "department is empty!";
        QMessageBox::critical(this, "error", error_str);
        return;
    }
    else if(this->ui->salary_line->text().isEmpty())
    {
        QString error_str = "salary is empty!";
        QMessageBox::critical(this, "error", error_str);
        return;
    }
    char send_info[512] = {0};
    sprintf(send_info,"%d",add_protocol);
    QByteArray name = this->ui->name_line->text().toUtf8();
    int old = this->ui->old_line->text().toInt();
    QByteArray department = this->ui->department_line->text().toUtf8();
    int salary = this->ui->salary_line->text().toInt();
    trans_dbinfo_t myinfo;
    strcpy(myinfo.name,name.data());
    myinfo.old = old;
    strcpy(myinfo.department,department.data());
    myinfo.salary = salary;

    memcpy(send_info + 2,&myinfo,sizeof(myinfo));

    this->socket->write(send_info,sizeof(send_info));
}

void Add::my_add_slot(bool is_root)
{
    this->show();
    if(is_root)
    {
        this->ui->salary_line->setReadOnly(false);
    }
    else
    {
        this->ui->salary_line->setReadOnly(true);
    }
}

void Add::on_back_btn_clicked()
{
    emit this->my_back_to_hrORmanagerop_signal();
    this->hide();
    this->ui->name_line->clear();
    this->ui->old_line->clear();
    this->ui->department_line->clear();
    this->ui->salary_line->setText(QString("0"));
}
